package cn.minhx.dtm.starter.core.task;

import cn.minhx.dtm.starter.config.DistributedTransactionProperties;
import cn.minhx.dtm.starter.core.service.TransactionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 分布式事务重试定时任务
 *
 * @author min
 */
public class TransactionRetryTask {

	private static final Logger log = LoggerFactory.getLogger(TransactionRetryTask.class);

	private final TransactionService transactionService;
	private final DistributedTransactionProperties properties;

	public TransactionRetryTask(TransactionService transactionService, DistributedTransactionProperties properties) {
		this.transactionService = transactionService;
		this.properties = properties;
	}

	/** 定时重试失败的事务 */
	@Scheduled(fixedDelayString = "${dtm.retry.scan-interval:30000}")
	public void retryFailedTransactions() {
		if (!properties.isEnabled()) {
			return;
		}
		log.debug("开始扫描需要重试的事务...");
		try {
			transactionService.retryFailedTransactions(properties.getRetry().getBatchSize());
		} catch (Exception e) {
			log.error("事务重试任务执行出错", e);
		}
	}
}
